package com.wskj.shiro;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.wskj.pojo.User;

public class DatabaseRealm extends AuthorizingRealm{

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		
		String userName = principalCollection.getPrimaryPrincipal().toString();
		
		Set<String> roles = new UserDao().listRoles(userName);
		
		Set<String> permissions = new UserDao().listPermissions(userName);
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roles);
		info.setStringPermissions(permissions);
		return info;
	}

	@Override
	/*protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		// TODO Auto-generated method stub
		
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		
		String username = token.getPrincipal().toString();
		String password = new String(token.getPassword());
		
		
		String passwordBD = new UserDao().getPassword(username);
		
		if(passwordBD == null  || !passwordBD.equals(password)){
			throw new AuthenticationException();
		}
		AuthenticationInfo info = new SimpleAuthenticationInfo(username,password,getName());
		
		return info;
	}*/
	
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		// TODO Auto-generated method stub
		
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		
		String username = token.getPrincipal().toString();
		String password = new String(token.getPassword());
		
		User user = new UserDao().getUser(username);
		String salt = user.getSalt();
		
		
		String passwordBD = new UserDao().getPassword(username);
		
		if(passwordBD == null  ){
			throw new AuthenticationException();
		}
		AuthenticationInfo info = new SimpleAuthenticationInfo(username,passwordBD,ByteSource.Util.bytes(salt),getName());
		
		return info;
	}
	

}
